package.path = package.path .. ";/usr/local/share/lua/5.3/?.lua"
package.cpath = package.cpath .. ";/usr/local/lib/lua/5.3/?.so"
require('init')
local luasql = require('luasql.mysql')
local cjson = require("cjson")

--加载配置文件
local function load_config_file(filename)
    file = io.open(filename)
    if not file then
        error("open " .. filename .. " failed: " .. (err or "unknown error"))
        return
    end
    local content = file:read('*a')
    file:close()
    return cjson.decode(content)
end

local config = load_config_file("../config/config.json")

-- MySQL配置
local mysql_db = config.mysql_db
local mysql_username = config.mysql_username
local mysql_password = config.mysql_password
local mysql_host = config.mysql_host
local mysql_port = config.mysql_port

--创建环境对象
local env = luasql.mysql()

--连接数据库
local conn,err = env:connect(mysql_db,mysql_username,mysql_password,mysql_host,mysql_port)
if not conn then
    error("connect to database failed: " .. err)
    return
else
    print("connect mysql server success")
end

--设置数据库的编码格式
conn:execute("set names utf-8")

--统计该IP是第几个访问的以及该页面总的访问次数
function getPageVisitedCount(ip)
    local sql1 = string.format("select * from users where ip = '" .. ip .. "'")
    local cur1, err = conn:execute(sql1)

    -- 检查 cur1 是否为 nil
    if not cur1 then
        error("execute query failed: " .. (err or "unknown error"))
    end
    local insert_order
    local total_count

    local row1 = cur1:fetch({},"a")
    --如果查询的结果为空,则进行插入
    if not row1 then
        -- local insert_sql = string.format("insert into users (ip,count) values (%s,1)",ip)
        local insert_sql = string.format("insert into users (ip,count) values ('" .. ip .. "',1)")
        conn:execute(insert_sql)
        local id = conn:execute("select LAST_INSERT_ID()"):fetch({},"a").LAST_INSERT_ID
        insert_order = id

        local sql2 = string.format("select sum(count) as total_count from users")
        local cur2 = conn:execute(sql2)
        local row2 = cur2:fetch({},"a")
        total_count = row2.total_count
    --不为空,则将对对应的次数进行++
    else
        insert_order = row1.id

        local update_sql = string.format("update users set count = count + 1 where ip = '" .. ip .. "'")
        conn:execute(update_sql)

        local sql3 = "select sum(count) as total_count from users"
        local cur3 = conn:execute(sql3)
        local row3 = cur3:fetch({},"a")
        total_count = row3.total_count
    end

    return insert_order,total_count
end


--读取文件内容
local function read_file(filename)
    local file = io.open(filename,"r")
    if not file then
        error("open " .. filename .. "failed")
    end
    local content = file:read("*a")
    file:close()
    return content
end

--构建HTTP响应内容
function generate_http_response(ip)
    local visitor_number, visited_count = getPageVisitedCount(ip)
    local html_content = read_file("../wwwroot/template.html")

    -- print("visited_count: " .. tostring(visited_count))
    -- print("visitor_number: " .. tostring(visitor_number))

    -- 替换占位符
    -- 需要对html中的-进行转义
    html_content = html_content:gsub("<!%-%- PAGE_REQUEST_COUNT %-%->", tostring(visited_count))
    html_content = html_content:gsub("<!%-%- USER_VISITED_ORDER %-%->", tostring(visitor_number))
    return html_content
end